/*
** client_echo.c
*/

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/times.h>
#include <sys/timeb.h>
#include <unistd.h>

#define PORT 3477    /* the port client will be connecting to */

#define MAXDATASIZE 100 /* max number of bytes we can get at once */

double difftimeb (struct timeb* end, struct timeb* begin);

int main(int argc, char *argv[])
{
    int sockfd, numbytes;
    int sent_nl=0, recv_nl=0;
    int tschar=0, trchar=0, bgst_line=0;
    int ultima_linha;
    struct timeb t_init, t_end;  
    double t_total; 
    float ttime, cttime;
    char buf[MAXDATASIZE];
    struct hostent *he;
    struct sockaddr_in their_addr; /* connector's address information */
    FILE *wsock, *rsock;

    if (argc != 2) {
        fprintf(stderr,"usage: client hostname\n");
        exit(1);
    }
    if ((he=gethostbyname(argv[1])) == NULL) {  /* get the host info */
        perror("gethostbyname");
        exit(1);
    }
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    wsock = fdopen (sockfd, "w");
    rsock = fdopen (sockfd, "r");

    their_addr.sin_family = AF_INET;                        /* host byte order              */
    their_addr.sin_port = htons(PORT);                      /* short, network byte order    */
    their_addr.sin_addr = *((struct in_addr *)he->h_addr);
    bzero(&(their_addr.sin_zero), 8);                       /* zero the rest of the struct  */

    printf("1\n");

    if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {
      perror("connect");
      exit(1);
    }

    while (waitpid(-1, NULL, WNOHANG) > 0);

    printf("client: conectado em %s\n", argv[1]);

    ftime(&t_init);
    if (!fork()) {      
      while (fgets (buf, MAXDATASIZE, stdin)) {
	fputs(buf, wsock) == EOF;
	fflush(wsock);

	sent_nl++;
	ultima_linha = strlen(buf);
	tschar += ultima_linha;

	if (ultima_linha > bgst_line)
	  bgst_line = ultima_linha;
      }
      shutdown (sockfd, SHUT_WR);
      
      exit(1);     
    }
    
    while (fgets(buf, MAXDATASIZE, rsock)) {
      recv_nl++;
      trchar += strlen(buf);
      fputs (buf, stdout);
    }
    ftime(&t_end);

    t_total=difftimeb(&t_end, &t_init);
    
    fprintf(stderr, "tempo total: %lf\n", t_total);

    wait (NULL);
    close (sockfd);
    

    return 0;   
}
